package org.gangcai.mac.shop.activity;

import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.just.agentweb.AgentWeb;

import org.gangcai.mac.shop.R;
import org.gangcai.mac.shop.bean.GoodInfoDetail;
import org.gangcai.mac.shop.common.MultiStatusActivity;
import org.gangcai.mac.shop.constants.Constant;
import org.gangcai.mac.shop.holders.LocalImageHolderView;
import org.gangcai.mac.shop.manager.RetrofitManager;
import org.gangcai.mac.shop.oberver.CommonObserver;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;

import static org.gangcai.mac.shop.constants.Constant.CODE_SUCC;

public class ShopDetailActivity extends MultiStatusActivity {

    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @BindView(R.id.shopTitle)
    TextView shopTitle;
    @BindView(R.id.container)
    LinearLayout container;
    @BindView(R.id.btn)
    Button btn;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.sfhsj)
    TextView sfhsj;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.webView)
    WebView webView;
    private String id;
    private GoodInfoDetail goodInfo;
    private AgentWeb mAgentWeb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        id = getIntent().getExtras().getString("id");
        initTitleBarView(titlebar, "商品详情");
//        addWebView(content);
        loadData();
    }

    private void loadData() {
        multipleStatusView.showLoading();
        RetrofitManager.create().goods_info(id)
                .compose(this.<GoodInfoDetail>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CommonObserver<GoodInfoDetail>(multipleStatusView) {
                    @Override
                    public void onSuccess(GoodInfoDetail value) {

                        if (value.getCode() == CODE_SUCC) {
                            goodInfo = value;
                            ArrayList<String> viewpageDatas = new ArrayList<>();
                            viewpageDatas.add(Constant.IMAGE_PATH + value.getImg().getImg_one());
                            viewpageDatas.add(Constant.IMAGE_PATH + value.getImg().getImg_two());
                            viewpageDatas.add(Constant.IMAGE_PATH + value.getImg().getImg_three());
                            setViewPagerData(viewpageDatas);
                            shopTitle.setText(value.getGoods_name());
                            money.setText("¥" + value.getMoney());
                            sfhsj.setText("三方回收价 : ¥" + value.getBack_money());
                            addWebView(value.getGoods_intro());
                        }
                    }
                });

   /*     for (int i = 0; i < viewpageDatas.size(); i++) {

            String s = viewpageDatas.get(i);
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(300)));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            Glide.with(this).load(s).into(imageView);
            imageContainer.addView(imageView);

        }*/


    }

    private void addWebView(String content) {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                view.loadUrl(url);
                return true;
            }


            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return super.shouldInterceptRequest(view, url);
            }

        });
//        webView.loadData(content, "text/html; charset=UTF-8" ,null);
        webView.loadUrl(RetrofitManager.server_address + "goods_intro?id=" + id);
        webView.setHorizontalFadingEdgeEnabled(false);
        webView.setVerticalFadingEdgeEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();

//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

//支持插件
//        webSettings.setPluginsEnabled(true);

//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

//缩放操作
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(false); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

//其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
     /*   mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go("http://www.jd.com");

        final WebView wv = mAgentWeb.getWebCreator().getWebView();*/
      /*  wv.setOnTouchListener(new View.OnTouchListener() {

            private float startx;
            private float starty;
            private float offsetx;
            private float offsety;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        v.getParent().requestDisallowInterceptTouchEvent(true);
                        startx = event.getX();
                        starty = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:

                        boolean scrollDown = scrollView.canScrollVertically(1);
                        boolean scrollUp = wv.canScrollVertically(-1);
                        if (!scrollDown) {
                            v.getParent().requestDisallowInterceptTouchEvent(true);
                        }

                        if (!scrollUp) {
                            v.getParent().requestDisallowInterceptTouchEvent(false);
                        }

                        break;
                    default:
                        break;
                }
                return false;
            }
        });*/

     /*   wv.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        wv.setVerticalScrollBarEnabled(false);
        wv.setVerticalScrollbarOverlay(false);
        wv.setHorizontalScrollBarEnabled(false);
        wv.setHorizontalScrollbarOverlay(false);*/

    }

    private void setViewPagerData(List<String> data) {
        convenientBanner.setPages(
                new CBViewHolderCreator<LocalImageHolderView>() {
                    @Override
                    public LocalImageHolderView createHolder() {
                        return new LocalImageHolderView();
                    }
                }, data)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.indicator_normal, R.mipmap.indicator_focus})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
        convenientBanner.startTurning(5000);
        convenientBanner.setScrollDuration(3000);
        try {
            Class<?> clazz = Class.forName("com.bigkoo.convenientbanner.ConvenientBanner");
            Field loPageTurningPoint = clazz.getDeclaredField("loPageTurningPoint");
            loPageTurningPoint.setAccessible(true);
            ViewGroup o = (ViewGroup) loPageTurningPoint.get(convenientBanner);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) o.getLayoutParams();
            layoutParams.bottomMargin = SizeUtils.dp2px(36);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getContentView() {
        return R.layout.activity_shop_detail;
    }

    @OnClick(R.id.btn)
    public void onViewClicked() {
        if (goodInfo != null) {

            Bundle bundle = new Bundle();
            bundle.putString("gid", goodInfo.getId());
            ActivityUtils.startActivity(bundle, this, ConfirmOrderActivity.class);
        }
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();

            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }
}
